import axios from 'axios'
import router from '@router'
import store from '@store'

const http = axios.create({
  baseURL: process.env.BASEURL,
  timeout: 30000
})
axios.defaults.withCredentials = true

http.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/json'
  // set token
  return config
}, error => {
  console.log(error)
  return Promise.reject(error)
})

http.interceptors.response.use(
  response => {
    let data = response.data
    let { status } = data
    if (status.index === '40001') {
      router.push({
        path: '/sign'
      })
      return Promise.reject(data)
    } else {
      let { token } = data
      // localStorage.setItem('token', token)
      if (token) {
        store.dispatch('user/token', token)
      }
      return data
    }
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  })

export default http
